package com.suket.jnn;

import java.util.Iterator;
import java.util.List;

import org.apache.log4j.Level;
import org.apache.log4j.Logger;

public class NetworkSupport {

  static Logger logger = Logger.getLogger(NetworkSupport.class);

  public static String info( Network network ) {
    String result = "";
    if ( !verifyNetwork(network) ) {
      logger.log(Level.WARN, "Failed to perform info , found invalid network");
      return result;
    }

    Layer inputLayer = network.getInputLayer();
    result += CommonUtil.tab(2) + inputLayer.getName() + ": ";
    String info = LayerSupport.info(inputLayer, 4);
    result += info + "\n";

    List listHiddenLayers = network.getHiddenLayers();
    Iterator iterHiddenLayers = listHiddenLayers.iterator();
    while ( iterHiddenLayers.hasNext() ) {
      Layer hiddenLayer = (Layer) iterHiddenLayers.next();
      result += CommonUtil.tab(2) + hiddenLayer.getName() + ": ";
      info = LayerSupport.info(hiddenLayer, 4);
      result += info + "\n";
    }

    Layer outputLayer = network.getOutputLayer();
    result += CommonUtil.tab(2) + outputLayer.getName() + ": ";
    info = LayerSupport.info(outputLayer, 4);
    result += info + "\n";

    return result;
  }

  public static String infoWeights( Network network ) {
    String result = "";
    if ( !verifyNetwork(network) ) {
      logger.log(Level.WARN, "Failed to perform info weights "
          + ", found invalid network");
      return result;
    }
    List listHiddenLayers = network.getHiddenLayers();

    Iterator iterHiddenLayers = listHiddenLayers.iterator();
    while ( iterHiddenLayers.hasNext() ) {
      Layer hiddenLayer = (Layer) iterHiddenLayers.next();
      result += CommonUtil.tab(2) + hiddenLayer.getName() + ": \n";
      String infoLayerWeights = LayerSupport.infoWeights(hiddenLayer, 4);
      result += infoLayerWeights;
    }

    Layer outputLayer = network.getOutputLayer();
    result += CommonUtil.tab(2) + outputLayer.getName() + ": \n";
    String infoLayerWeights = LayerSupport.infoWeights(outputLayer, 4);
    result += infoLayerWeights;

    return result;
  }

  public static boolean verifyNetwork( Network network ) {
    boolean result = false;
    if ( network == null ) {
      logger.log(Level.ERROR, "Found null network");
      return result;
    }
    Layer ilyr = network.getInputLayer();
    if ( ilyr == null ) {
      logger.log(Level.ERROR, "Found null input layer");
      return result;
    }
    List hlyrs = network.getHiddenLayers();
    if ( ( hlyrs == null ) || ( hlyrs.size() < 1 ) ) {
      logger.log(Level.ERROR, "Found null / empty hidden layers");
      return result;
    }
    Layer olyr = network.getOutputLayer();
    if ( olyr == null ) {
      logger.log(Level.ERROR, "Found null output layer");
      return result;
    }
    result = true;
    return result;
  }

}
